package org.thanos.demo.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thanos.demo.file.FileService;
import org.thanos.demo.mongo.DemoEntity;
import org.thanos.demo.mongo.MongoService;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    private MongoService mongoService;

    @Autowired
    private FileService fileService;

    @GetMapping("/findAll")
    public List<DemoEntity> findAll() {
        return mongoService.findAll();
    }

    @GetMapping("/insert")
    public Map insert() {
        mongoService.insert();
        return Collections.singletonMap("result", true);
    }

    @GetMapping("/delete")
    public Map delete() {
        mongoService.delete();
        return Collections.singletonMap("result", true);
    }

    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        try {
            String fileName = fileService.uploadFile(file);
            response.setStatus(HttpStatus.OK.value());
            return fileName;
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    @GetMapping("/downloadFile/{id}")
    public void downloadFile(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
        try {
            fileService.downloadFile(id, request, response);
            response.setStatus(HttpStatus.OK.value());
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

}
